package spring.security.core.validatecode;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import spring.security.core.validatecode.service.SmsCodeSender;
import spring.security.core.validatecode.service.ValidateCodeGenerator;

@RestController
@RequestMapping("/code")
public class ValidateCodeController {

	public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE_";
	
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
	
	@Autowired
	private ValidateCodeGenerator imageCodeGenerator;
	@Autowired
	private ValidateCodeGenerator smsCodeGenerator;
	@Autowired
	private SmsCodeSender smsCodeSender;
	
	@GetMapping("/image")
	public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//创建图片文件
		ImageCode imageCode = (ImageCode) imageCodeGenerator.generate(new ServletWebRequest(request));
		//保存
		ValidateCodeCode tempCode = new ValidateCodeCode(imageCode.getCode(), imageCode.getExpireTime());
		sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY + "IMAGE", tempCode);
		//写出去
		ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
	}
	
	@GetMapping("/sms")
	public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//创建短信验证码
		ValidateCodeCode code = smsCodeGenerator.generate(new ServletWebRequest(request));
		//保存
		sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY + "SMS", code);
		String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
		smsCodeSender.send(mobile, code.getCode());
	}
	
}
